let selectedFiles = [];
let currentKbName = '';

document.getElementById('docUpload').addEventListener('change', function (e) {
    if (e.target.files.length > 0) {
        selectedFiles = Array.from(e.target.files);
        document.getElementById('fileNames').textContent = selectedFiles.map(f => f.name).join(', ');
    }
});

document.getElementById('kbSelector').addEventListener('change', function (e) {
    const selectedKb = e.target.value;
    if (!selectedKb) return;

    const chatHistory = document.getElementById('chatHistory');
    const hasHistory = chatHistory.children.length > 1 ||
        (chatHistory.children.length === 1 &&
            !chatHistory.children[0].textContent.includes('您好！'));

    if (hasHistory) {

        const originalValue = sessionStorage.getItem('currentKbName') || '';
        const confirmBox = document.getElementById('customConfirm');

        confirmBox.classList.remove('hidden');

        const confirmHandler = (result) => {
            confirmBox.classList.add('hidden');
            if (!result) {
                e.target.value = originalValue;
                return;
            }

            chatHistory.innerHTML = `<div class="message bot-message">
                    <div class="message-logo">
                        <img src="/static/AIrobot.svg" width="32" height="32" class="bot-logo">
                    </div>
                    <div class="message-content">您好！请问有什么可以帮助您的？</div>
                </div>`;


            sessionStorage.setItem('currentKbName', selectedKb);
            fetch('/clear_history', { method: 'POST' }).catch(console.error);
        };

        confirmBox.querySelector('.confirm-btn-primary').onclick = () => confirmHandler(true);
        confirmBox.querySelector('.cancel-btn').onclick = () => confirmHandler(false);
    } else {
        sessionStorage.setItem('currentKbName', selectedKb);
    }
});


async function handleUpload() {
    const submitBtn = document.querySelector('.submit-btn');
    submitBtn.innerHTML = '<div class="loader"></div> 分析中...';
    submitBtn.disabled = true;

    // 展示进度条
    const progressBarContainer = document.getElementById('uploadProgressContainer');
    const progressBar = document.getElementById('uploadProgressBar');
    progressBarContainer.classList.remove('hidden');
    progressBar.style.width = '0%';
    progressBar.textContent = '0%';
    progressBar.style.backgroundColor = '#4caf50';

    const kbName = document.getElementById('kbNameInput').value.trim();
    const fileInput = document.getElementById('docUpload');

    if (!kbName || !fileInput.files.length) {
        showNotification('请填写知识库名称并选择文件', 'error');
        submitBtn.innerHTML = '提交分析';
        submitBtn.disabled = false;
        return;
    }

    const formData = new FormData();
    formData.append('kbName', kbName);
    Array.from(fileInput.files).forEach(file => {
        formData.append('file', file);
    });

    let progress = 0;
    let intervalId = null;

    try {
        const controller = new AbortController();
        const signal = controller.signal;

        const responsePromise = fetch('/upload', {
            method: 'POST',
            body: formData,
            signal
        });

        intervalId = setInterval(() => {
            if (progress < 99) {
                progress += 1;
                progressBar.style.width = progress + '%';
                progressBar.textContent = progress + '%';
            }
        }, 300); // 每300ms更新一次

        const response = await responsePromise;

        clearInterval(intervalId);

        const data = await response.json();

        if (response.ok) {
            // 成功后进度跳到100%
            progressBar.style.width = '100%';
            progressBar.textContent = '100%';
            progressBar.style.backgroundColor = '#43a047';

            const kbSelector = document.getElementById('kbSelector');
            const newOption = document.createElement('option');
            newOption.value = data.kb_name;
            newOption.textContent = data.kb_name;
            kbSelector.appendChild(newOption);

            kbSelector.value = data.kb_name;

            updateAnalysisResults(data);
            showNotification('文档上传成功', 'success');

            fileInput.value = '';
            document.getElementById('fileNames').textContent = '';
            document.getElementById('kbNameInput').value = '';
            sessionStorage.setItem('currentKbName', data.kb_name);
        } else {
            progressBar.textContent = '上传失败';
            progressBar.style.backgroundColor = '#e53935';
            showNotification(data.error || '上传失败', 'error');
        }
    } catch (error) {
        if (intervalId) clearInterval(intervalId);
        progressBar.textContent = '网络错误';
        progressBar.style.backgroundColor = '#e53935';
        showNotification('网络错误，请重试', 'error');
    } finally {
        submitBtn.innerHTML = '提交分析';
        submitBtn.disabled = false;
    }
}


function updateAnalysisResults(data) {
    const results = document.getElementById('analysisResults');
    results.innerHTML = `
                <div class="document-info">
                    ${Object.entries(data.docInfo).map(([key, value]) => `
                        <div class="info-item">
                            <h4>${key}</h4>
                            <p>${value}</p>
                        </div>
                    `).join('')}
                </div>
                <div class="summary-section">
                    <h3>文档摘要</h3>
                    <p>${data.abstract}</p>
                </div>
                <div class="structure-section">
                    <h3>文档结构</h3>
                    <div class="structure-content">${data.hierarchyHTML}</div>
                </div>
            `;
}

async function sendMessage() {
    const input = document.getElementById('chatInput');
    const message = input.value.trim();
    const history = document.getElementById('chatHistory');
    const kbSelector = document.getElementById('kbSelector');
    const selectedKb = kbSelector.value;

    if (!selectedKb || selectedKb === "") {
        showNotification('请先选择知识库', 'error');
        return;
    }

    if (!message) return;

    const userMsg = document.createElement('div');
    userMsg.className = 'message user-message';
    userMsg.innerHTML = `
                <div class="message-content">${message}</div>
            `;
    history.appendChild(userMsg);

    const loader = document.createElement('div');
    loader.className = 'message bot-message';
    loader.innerHTML = '<div class="loader"></div>';
    history.appendChild(loader);

    input.value = '';
    history.scrollTop = history.scrollHeight;

    try {
        const response = await fetch('/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                message: message,
                kb_name: selectedKb
            })
        });

        const data = await response.json();
        loader.remove();

        if (response.ok) {
            const botMsg = document.createElement('div');
            botMsg.className = 'message bot-message';
            botMsg.innerHTML = `                        
                <div class="message-logo">
                    <img src="/static/AIrobot.svg" width="32" height="32" class="bot-logo">
                </div>
                <div class="message-content">${data.response}</div>
            `;
            history.appendChild(botMsg);
        } else {
            showNotification(data.error || '请求失败', 'error');
        }
    } catch (error) {
        loader.remove();
        showNotification('网络错误，请重试', 'error');
    }

    history.scrollTop = history.scrollHeight;
}

function showPage(pageId) {
    document.getElementById('uploadPage').classList.toggle('hidden', pageId !== 'upload');
    document.getElementById('chatPage').classList.toggle('hidden', pageId !== 'chat');
}

function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;

    const iconMap = {
        error: `<svg class="notification-icon" viewBox="0 0 24 24" fill="#ff4444">
                    <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/>
                </svg>`,
        success: `<svg class="notification-icon" viewBox="0 0 24 24" fill="#4CAF50">
                    <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
                </svg>`
    };

    notification.innerHTML = `
            ${iconMap[type] || ''}
            <span>${message}</span>
        `;

    document.body.appendChild(notification);
    setTimeout(() => notification.classList.add('show'), 10);

    setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => notification.remove(), 300);
    }, 3000);

    notification.addEventListener('mouseenter', () => {
        notification.style.animationPlayState = 'paused';
    });

    notification.addEventListener('mouseleave', () => {
        notification.style.animationPlayState = 'running';
    });
}